<?php
/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2007 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */

defined('IN_ADMIN_COMPONENT_CONTROLLER') or die();

require_once('includes/functions/configuration_functions.php');

class EditAccountComponent
{
	function EditAccountComponent()
	{
	}

	function action(&$params, $action)
	{
		require_once('includes/components/AccountComponent.php');

		if ($action == 'CreateAccount' || $action == 'EditAccount'
		|| $action == 'AddressBook' || $action == 'DeleteAddress') 
			return $this->edit($params);
		else if ($action == 'DeleteAccount') 
			return $this->deleteAccount($params);
		else 
			return $this->query($params);
	}

	function query(&$params)
	{
		$handle = get_class($this);
		$accountId = (int)$params['editAccountId'];

		if ($accountId == -1) {
			$value{$handle}{0}{'id'}= $accountId;
		}

		$component = new AccountComponent();
		
		$subParams['superHandle'] = $handle;
		$subParams['accountId'] = $accountId;
		$subParams['languageId'] = (int)$params['languageId'];
		$subParams['addressId'] = $params['addressId'];
		$subParams['gender'] = $params['gender'];
		$subParams['firstname'] = $params['firstname'];
		$subParams['lastname'] = $params['lastname'];
		$subParams['dob'] = $params['dob'];
		$subParams['email_address'] = $params['email_address'];
		$subParams['company'] = $params['company'];
		$subParams['street_address'] = $params['street_address'];
		$subParams['suburb'] = $params['suburb'];
		$subParams['postcode'] = $params['postcode'];
		$subParams['city'] = $params['city'];
		$subParams['state'] = $params['state'];
		$subParams['country'] = $params['country'];
		$subParams['telephone'] = $params['telephone'];
		$subParams['fax'] = $params['fax'];
		$subParams['newsletter'] = $params['newsletter'];
		$subParams['accountErrorCode'] = $params['accountErrorCode'];
		$value = $component->query($subParams);

		return $value;
	}

	function edit(&$params)
	{
		$display_company = returnBoolean(ACCOUNT_COMPANY);
		$display_dob = returnBoolean(ACCOUNT_DOB);
		$display_gender = returnBoolean(ACCOUNT_GENDER);
		$display_state = returnBoolean(ACCOUNT_STATE);
		$display_suburb = returnBoolean(ACCOUNT_SUBURB);
		$entry_city_length_min = (int)ENTRY_CITY_MIN_LENGTH;
		$entry_email_address_length_min = (int)ENTRY_EMAIL_ADDRESS_MIN_LENGTH;
		$entry_firstname_length_min = (int)ENTRY_FIRST_NAME_MIN_LENGTH;
		$entry_lastname_length_min = (int)ENTRY_LAST_NAME_MIN_LENGTH;
		$entry_postcode_length_min = (int)ENTRY_POSTCODE_MIN_LENGTH;
		$entry_state_length_min = (int)ENTRY_STATE_MIN_LENGTH;
		$entry_street_address_length_min = (int)ENTRY_STREET_ADDRESS_MIN_LENGTH;
		$entry_telephone_length_min = (int)ENTRY_TELEPHONE_MIN_LENGTH;
		$address_book_entries_max = (int)MAX_ADDRESS_BOOK_ENTRIES;

		$action = prepare_input($params['action']);
		$accountId = (int)$params['editAccountId'];
		$addressId = (int)$params['addressId'];
		$gender = prepare_input($params['gender']);
		$firstname = prepare_input($params['firstname']);
		$lastname = prepare_input($params['lastname']);
		$dob = (int)$params['dob'];
		$dob = (int)$dob/1000.00;
		$emailAddress = prepare_input($params['email_address']);
		$company = prepare_input($params['company']);
		$streetAddress = prepare_input($params['street_address']);
		$suburb = prepare_input($params['suburb']);
		$postcode = prepare_input($params['postcode']);
		$city = prepare_input($params['city']);
		$state = prepare_input($params['state']);
		$country = prepare_input($params['country']);
		$telephone = prepare_input($params['telephone']);
		$fax = prepare_input($params['fax']);
		$newsletter = (int)$params['newsletter'];

		if ($gender == null) $gender = '';
		if ($firstname == null) $firstname = '';
		if ($lastname == null) $lastname = '';
		if ($emailAddress == null) $emailAddress = '';
		if ($company == null) $company = '';
		if ($streetAddress == null) $streetAddress = '';
		if ($suburb == null) $suburb = '';
		if ($postcode == null) $postcode = '';
		if ($city == null) $city = '';
		if ($state == null) $state = '';
		if ($country == null) $country = '';
		if ($telephone == null) $telephone = '';
		if ($fax == null) $fax = '';

		$required_fields_available = true;
		if ($required_fields_available && ($accountId == 0 || strlen($gender) > 0) && $display_gender && !($gender == 'm' || $gender == 'f')) $required_fields_available = false;
		if (!$required_fields_available) {$params['accountErrorCode'] = -40; return $this->query($params);}
		if ($required_fields_available && ($accountId == 0 || strlen($firstname) > 0) && strlen($firstname) < $entry_firstname_length_min) $required_fields_available = false;
		if (!$required_fields_available) {$params['accountErrorCode'] = -41; return $this->query($params);}
		if ($required_fields_available && ($accountId == 0 || strlen($lastname) > 0) && strlen($lastname) < $entry_lastname_length_min) $required_fields_available = false;
		if (!$required_fields_available) {$params['accountErrorCode'] = -42; return $this->query($params);}

		if ($required_fields_available && ($accountId == 0 || strlen($emailAddress) > 0) && strlen($emailAddress) < $entry_email_address_length_min) $required_fields_available = false;
		if (!$required_fields_available) {$params['accountErrorCode'] = -43; return $this->query($params);}

		if ($required_fields_available && ($accountId == 0 || strlen($streetAddress) > 0) && strlen($streetAddress) < $entry_street_address_length_min) $required_fields_available = false;
		if (!$required_fields_available) {$params['accountErrorCode'] = -44; return $this->query($params);}
		if ($required_fields_available && ($accountId == 0 || strlen($postcode) > 0) && strlen($postcode) < $entry_postcode_length_min) $required_fields_available = false;
		if (!$required_fields_available) {$params['accountErrorCode'] = -45; return $this->query($params);}
		if ($required_fields_available && ($accountId == 0 || strlen($city) > 0) && strlen($city) < $entry_city_length_min) $required_fields_available = false;
		if (!$required_fields_available) {$params['accountErrorCode'] = -46; return $this->query($params);}
		if ($required_fields_available && ($accountId == 0 || strlen($state) > 0) && $display_state && strlen($state) < $entry_state_length_min) $required_fields_available = false;
		if (!$required_fields_available) {$params['accountErrorCode'] = -47; return $this->query($params);}
		if ($required_fields_available && ($accountId == 0 || strlen($telephone) > 0) && strlen($telephone) < $entry_telephone_length_min) $required_fields_available = false;
		if (!$required_fields_available) {$params['accountErrorCode'] = -48; return $this->query($params);}

		$exists = false;
		$sqlQuery = 'select customers_id from ' . TABLE_CUSTOMERS . ' where customers_email_address = \'' . mysql_real_escape_string($emailAddress) . '\'';
		if ($accountId > 0) $sqlQuery = 'select customers_id from ' . TABLE_CUSTOMERS . ' where customers_id = \'' . $accountId . '\'';
		$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
		$i = 0;
		while($row = mysql_fetch_array($dataReturned))
		{
			$db_accountId = (int)$row['customers_id'];
			$i++;
			break;
		}
		if ($i > 0) $exists = true;

		if ($accountId == 0 && $exists)
		{
			$params['accountErrorCode'] = -50;
			return $this->query($params);
		}
		else if ($accountId > 0 && !$exists)
		{
			$params['accountErrorCode'] = -60;
			return $this->query($params);
		}
		else if ($accountId > 0 && $exists && $accountId != $db_accountId)
		{
			$params['accountErrorCode'] = -70;
			return $this->query($params);
		}

		$country_id = 0;
		$zone_id = 0;
		if (strlen($country) > 0)
		{
			$sqlQuery = 'select countries_id from . ' . TABLE_COUNTRIES . ' where countries_name = \'' . mysql_real_escape_string($country) . '\'';
			$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
			while($row = mysql_fetch_array($dataReturned))
			{
				$country_id = (int)$row['countries_id'];
				break;
			}
			if ($display_state && strlen($state) > 0)
			{
				$sqlQuery = 'select zone_id from ' . TABLE_ZONES . ' ' .
				'where zone_country_id = ' . $country_id . ' and zone_code = \'' . mysql_real_escape_string($state) . '\'';
				$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
				while($row = mysql_fetch_array($dataReturned))
				{
					$zone_id = $row['zone_id'];
				}
			}
		}

		//Update or Insert into Accounts Table.
		$sql_data_array = array();
		if (strlen($firstname) > 0) $sql_data_array['customers_firstname'] = $firstname;
		if (strlen($lastname) > 0)  $sql_data_array['customers_lastname'] = $lastname;
		if (strlen($emailAddress) > 0)  $sql_data_array['customers_email_address'] = $emailAddress;
		if (strlen($telephone) > 0)  $sql_data_array['customers_telephone'] = $telephone;
		if (strlen($fax) > 0)  $sql_data_array['customers_fax'] = $fax;
		if ($action == 'CreateAccount') {
			$sql_data_array['customers_newsletter'] = $newsletter;
			$password = random_generator(7);
			$sql_data_array['customers_password'] = encrypt_password($password);
			$sql_data_array['customers_isLogin'] = 0;
		}
		if ($display_gender && strlen($gender) > 0) $sql_data_array['customers_gender'] = $gender;
		if ($display_dob && $dob != 0) $sql_data_array['customers_dob'] = date('Ymd',$dob);

		$accountInserted = false;
		$accountEdited = false;

		if ($action == 'CreateAccount' || $action == 'EditAccount')
		{
			$sqlAction = 'insert';
			$where = '';
			if ($accountId > 0)
			{
				$sqlAction = 'update';
				$where = 'customers_id='.$accountId;
			}

			if (count($sql_data_array) > 0)
			{
				db_perform(TABLE_CUSTOMERS, $sql_data_array, $sqlAction, $where);
				if ($sqlAction == 'insert') {
					$accountInserted = true;
					$accountId = mysql_insert_id();
				}
				else {
					$accountEdited = true;
				}
			}
		}

		//Insert or Update the Address (maybe)
		$sqlAction = 'insert';
		if ($addressId > 0)
		{
			$sqlAction = 'update';

			//Does the Address Entry Exist?
			$sqlQuery = 'select address_book_id from ' . TABLE_ADDRESS_BOOK .
			' where address_book_id = ' . $addressId . ' and customers_id = ' . $accountId;
			$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
			$i = 0;
			while($row = mysql_fetch_array($dataReturned))
			{
				$i++;
				break;
			}
			if ($i == 0)
			{
				$params['accountErrorCode'] = -80;
				return $this->query($params);
			}
		}

		if ($action == 'DeleteAddress' && $addressId > 0)
		{
			//Don't delete primary address
			$defaultAddressId = 0;
			$sqlQuery = 'select customers_default_address_id from ' . TABLE_CUSTOMERS . ' where customers_id = ' . $accountId;
			$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
			while($row = mysql_fetch_array($dataReturned))
			{
				$defaultAddressId = (int)$row['customers_default_address_id'];
				break;
			}
			if ($defaultAddressId == $addressId)
			{
				$params['accountErrorCode'] = -85;
				return $this->query($params);
			}
			$sql = 'delete from ' . TABLE_ADDRESS_BOOK . ' where address_book_id = ' . $addressId;
			mysql_query($sql) or die(mysql_error());
			return $this->query($params);
		}

		if ($action == 'AddressBook' && $sqlAction == 'insert')
		{
			//Would adding this address mean too many?
			$sqlQuery = 'select address_book_id from ' . TABLE_ADDRESS_BOOK . ' where customers_id = ' . $accountId;
			$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
			$i = 0;
			while($row = mysql_fetch_array($dataReturned))
			{
				$i++;
			}
			if ($i > ($address_book_entries_max -1))
			{
				$params['accountErrorCode'] = -90;
				return $this->query($params);
			}
		}

		if ($action == 'CreateAccount' || $action == 'AddressBook')
		{
			$sql_data_array = array();
			if ($sqlAction == 'insert') $sql_data_array['customers_id'] = $accountId;
			if (strlen($firstname) > 0) $sql_data_array['entry_firstname'] = $firstname;
			if (strlen($lastname) > 0)  $sql_data_array['entry_lastname'] = $lastname;
			if (strlen($streetAddress) > 0)  $sql_data_array['entry_street_address'] = $streetAddress;
			if (strlen($postcode) > 0)  $sql_data_array['entry_postcode'] = $postcode;
			if (strlen($city) > 0)  $sql_data_array['entry_city'] = $city;
			if ($country_id > 0)  $sql_data_array['entry_country_id'] = $country_id;

			if ($display_gender && strlen($gender) > 0) $sql_data_array['entry_gender'] = $gender;
			if ($display_company && strlen($company) > 0) $sql_data_array['entry_company'] = $company;
			if ($display_suburb && strlen($suburb) > 0) $sql_data_array['entry_suburb'] = $suburb;

			if ($display_state)
			{
				if ($zone_id > 0)
				{
					$sql_data_array['entry_zone_id'] = $zone_id;
					$sql_data_array['entry_state'] = '';
				}
				else if (strlen($state) > 0)
				{
					$sql_data_array['entry_zone_id'] = '0';
					$sql_data_array['entry_state'] = $state;
				}
			}

			if ($sqlAction == 'update') $where = 'address_book_id = ' . $addressId;

			db_perform(TABLE_ADDRESS_BOOK, $sql_data_array, $sqlAction, $where);

			if ($sqlAction == 'insert') $addressId = mysql_insert_id();
		}

		if ($accountInserted) {
			$sql = 'update ' . TABLE_CUSTOMERS . ' set customers_default_address_id = \'' . (int)$addressId . '\' where customers_id = \'' . (int)$accountId . '\'';
			mysql_query($sql) or die(mysql_error());

			$sql = 'insert into ' . TABLE_CUSTOMERS_INFO . ' (customers_info_id, customers_info_number_of_logons, customers_info_date_account_created) values (\'' . $accountId . '\', \'0\', now())';
			mysql_query($sql) or die(mysql_error());
			
			$params['editAccountId'] = $accountId;

			//Newsletter Modules
			if ($newsletter == 1 && defined('MODULE_NEWSLETTER_INSTALLED') && MODULE_NEWSLETTER_INSTALLED != null && validate_email_format($emailAddress))
			{
				$newsletterParams['gender'] = $gender;
				$newsletterParams['firstname'] = $firstname;
				$newsletterParams['lastname'] = $lastname;
				$newsletterParams['dob'] = $dob;
				$newsletterParams['emailAddress'] = $emailAddress;
				$newsletterParams['telephone'] = $telephone;
				$newsletterParams['company'] = $company;
				$newsletterParams['postcode'] = $postcode;
				$newsletterParams['streetAddress'] = $streetAddress;
				$newsletterParams['city'] = $city;
				$newsletterParams['state'] = $state;
				$newsletterParams['country'] = $country;
		
				$modules = explode(';', MODULE_NEWSLETTER_INSTALLED);
				reset($modules);
				$i = 0;					
				while (list(, $value) = each($modules)) 
				{
					include_once('includes/modules/newsletter/' . $value);
					$class = substr($value, 0, strrpos($value, '.'));
					$obj = new $class;
					if ($obj != null && $obj->enabled)
					{
						$obj->process($newsletterParams);
						$i++;
					}
				}
			}
		}
		else if ($accountEdited) {
			$sql = 'update ' . TABLE_CUSTOMERS_INFO . ' set customers_info_date_account_last_modified=now() where customers_info_id=' . $accountId;
			mysql_query($sql) or die(mysql_error());
		}

		$params['accountErrorCode'] = 1;
		return $this->query($params);
	}

	function deleteAccount(&$params)
	{
		$accountId = (int)$params['editAccountId'];
		
		$sql = 'delete from ' . TABLE_CUSTOMERS . ' where customers_id=' . $accountId;
		mysql_query($sql) or die(mysql_error());

		$sql = 'delete from ' . TABLE_ADDRESS_BOOK . ' where customers_id=' . $accountId;
		mysql_query($sql) or die(mysql_error());

		$sql = 'delete from ' . TABLE_CUSTOMERS_BASKET . ' where customers_id=' . $accountId;
		mysql_query($sql) or die(mysql_error());

		$sql = 'delete from ' . TABLE_CUSTOMERS_BASKET_ATTRIBUTES . ' where customers_id=' . $accountId;
		mysql_query($sql) or die(mysql_error());

		$sql = 'delete from ' . TABLE_ROLES_TO_CUSTOMERS . ' where customers_id=' . $accountId;
		mysql_query($sql) or die(mysql_error());

		$params['action'] = 'query';
		$params['editAccountId'] = -1;
		return $this->query($params);
	}
}
?>
